package com.test;

import java.util.List;

import org.hibernate.*;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.criterion.Expression;

import com.model.UserLogin;

public class LoginDAO {

	public SessionFactory createSessionFactory() throws HibernateException {
		AnnotationConfiguration configuration = new AnnotationConfiguration();

		configuration.configure("com/hibernate.cfg.xml");

		return configuration.buildSessionFactory();

	}

	public long insertObject(SessionFactory factory) {
		UserLogin userLogin = new UserLogin();

		userLogin.setPassName("la");
		userLogin.setUserName("tro");

		Session session = factory.openSession();

		try {
			insertObject(session, userLogin);
		} finally {
			session.close();
		}

		return userLogin.getId_User();
	}

	private void insertObject(Session session, UserLogin userLogin) {
		boolean commit = false;
		Transaction transaction = session.beginTransaction();

		try {
			session.save(userLogin);

			commit = true;
		} finally {
			if (commit)
				transaction.commit();
			else
				transaction.rollback();
		}
	}

	public UserLogin getObject(SessionFactory factory, long id) {
		Session session = factory.openSession();

		try {
			return (UserLogin) session.load(UserLogin.class, id);
		} finally {
			session.close();
		}
	}

	public UserLogin queryObject(SessionFactory factory, String userName, String passName) {
		
		Session session = factory.openSession();

		try {
			Criteria criteria = session.createCriteria(UserLogin.class);

			criteria.add(Expression.eq("userName", userName));
			criteria.add(Expression.eq("passName", passName));

			List results = criteria.list();
			if (results.size() > 0) {
				return (UserLogin) results.get(0);
			} else {
				return null;
			}
			
		} finally {
			session.close();
		}
	}

}
